package org.apache.ocean.merge;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ocean.ClusterConstants;
import org.apache.ocean.IndexSchema;
import org.apache.ocean.OceanXML;
import org.apache.ocean.SearchRequest;
import org.apache.ocean.SearchRequestUtil;
import org.apache.ocean.SearchResponse;
import org.apache.ocean.TimeoutState;

/**
 * 
 * @author jasonr
 */
// TODO: add session parameter for tracking using didyoumean
public class MergeServlet extends HttpServlet {
	public static Logger log = Logger.getLogger(MergeServlet.class.getName());
	MergeService mergeService;

	public MergeServlet() {
	}

	public void init() throws ServletException {
		try {
			mergeService = MergeService.getMergeService();
		} catch (Throwable throwable) {
			log.log(Level.SEVERE, "", throwable);
		}
	}
  
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			IndexSchema indexSchema = mergeService.mergeNameClient.indexSchemaRef.getNoWait();
			SearchRequestUtil searchRequestUtil = new SearchRequestUtil(request, indexSchema);
			SearchRequest searchRequest = searchRequestUtil.getSearchRequest();
			TimeoutState timeoutState = null;
			if (searchRequest.timeout != null) {
				timeoutState = new TimeoutState(searchRequest.timeout);
			} else {
				timeoutState = TimeoutState.FOREVER();
			}
			searchRequest.termFrequencies = mergeService.mergeClient.getTermFrequencies(searchRequest.queryString, timeoutState);
			SearchResponse searchResponse = mergeService.mergeClient.search(searchRequest, timeoutState);
			OceanXML oceanXMLResponse = searchResponse.toOceanXML(indexSchema);
			response.setContentType(ClusterConstants.CONTENT_TYPE_XML);
		} catch (Throwable throwable) {
			log.log(Level.SEVERE, "", throwable);
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			IndexSchema indexSchema = null; // mergeService.mergeNameClient.
			
		} catch (Throwable throwable) {
			log.log(Level.SEVERE, "", throwable);
		}
	}
}
